/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.pizzaria.view;

import br.com.pizzaria.bean.AtualizaMovimentoEstoqueBean;
import br.com.pizzaria.bean.FornecedorBean;
import br.com.pizzaria.bean.ItemNotaFiscalEntradaBean;
import br.com.pizzaria.bean.ProdutoBean;
import br.com.pizzaria.bean.TipoProdutoBean;
import br.com.pizzaria.model.Estoque;
import br.com.pizzaria.model.PedidoModel;
import br.com.pizzaria.util.CentralizarForm;
import br.com.pizzaria.util.ConectaBanco;
import br.com.pizzaria.util.Global;
import br.com.pizzaria.util.LimiteDigitos;
import br.com.pizzaria.util.ValidaCNPJ;
import br.com.pizzaria.util.ValidaCPF;
import br.com.pizzaria.util.VerificarData;
import java.awt.event.KeyEvent;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.MaskFormatter;

/**
 *
 * @author Jaime
 */
public class NotaFiscalEntradaView extends javax.swing.JInternalFrame {

    MaskFormatter formatoNascimento;
    List<TipoProdutoBean> listaTipoProd;
    List<ProdutoBean> listaProduto;
    List<FornecedorBean> listaFornec;
    ComboBoxModel<TipoProdutoBean> modeloTipoProd;
    ComboBoxModel<ProdutoBean> modeloProduto;
    ComboBoxModel<FornecedorBean> modeloForncedor;
    DefaultTableModel modeloDeTabela;
    DecimalFormat decimalFormato;
    List<ItemNotaFiscalEntradaBean> listaDeItens;
    ComboBoxModel<Integer> comboNumPedido;
    int codigo;
    int codFonece;

    /**
     * Creates new form NotaFiscalEntradaView
     */
    public NotaFiscalEntradaView() {
        initComponents();
        modeloTipoProd = cbTipo.getModel();
        modeloProduto = cbProduto.getModel();
        modeloForncedor = cbFornecedor.getModel();
        txtDtEmissao.setText(VerificarData.retornoDeDataAtual());
        modeloDeTabela = (DefaultTableModel) tblProduto.getModel();
        decimalFormato = new DecimalFormat("0.00");
        
        txtNumNotaFiscal.setDocument(new LimiteDigitos(10));
        txtSerie.setDocument(new LimiteDigitos(3));
        comboNumPedido = cbPedCompra.getModel();
        
        populaListaFornecedor();
        populaTipoProduto();
//        pesquisaPedido();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        lbl_data3 = new javax.swing.JLabel();
        txtNumNotaFiscal = new javax.swing.JTextField();
        txtSerie = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        lbl_data2 = new javax.swing.JLabel();
        try{        formatoNascimento = new MaskFormatter("##/##/####");    }catch (Exception Erro){      JOptionPane.showMessageDialog(null, "Data inválida", "ERRO DE FORMATAÇÃO", 0);  }
        txtDtEmissao = new JFormattedTextField(formatoNascimento);
        try{        
            formatoNascimento = new MaskFormatter("##/##/####");    
        }catch (Exception Erro){      
            JOptionPane.showMessageDialog(null, "Data inválida", "ERRO DE FORMATAÇÃO", 0); 
        }
        txtDtReceb = new JFormattedTextField(formatoNascimento);
        lbl_data5 = new javax.swing.JLabel();
        lbl_data6 = new javax.swing.JLabel();
        txtCNPJ = new javax.swing.JTextField();
        lbl_data7 = new javax.swing.JLabel();
        cbFornecedor = new javax.swing.JComboBox();
        lblValor3 = new javax.swing.JLabel();
        txtTotalProdutosNota = new javax.swing.JTextField();
        lblValor4 = new javax.swing.JLabel();
        txtDescontoNota = new javax.swing.JTextField();
        lblValor5 = new javax.swing.JLabel();
        txtValorNota = new javax.swing.JTextField();
        lbl_data11 = new javax.swing.JLabel();
        cbPedCompra = new javax.swing.JComboBox();
        dcRecebimento = new com.toedter.calendar.JDateChooser();
        lbl_data10 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        lbl_data1 = new javax.swing.JLabel();
        cbTipo = new javax.swing.JComboBox();
        lbl_data8 = new javax.swing.JLabel();
        cbProduto = new javax.swing.JComboBox();
        lbl_data9 = new javax.swing.JLabel();
        txtUnidadeItem = new javax.swing.JTextField();
        txtRefProdItem = new javax.swing.JTextField();
        lblValor6 = new javax.swing.JLabel();
        lblValor7 = new javax.swing.JLabel();
        txtQtdeItem = new javax.swing.JTextField();
        lblValor8 = new javax.swing.JLabel();
        txtValorUnitarioItem = new javax.swing.JTextField();
        lblValor9 = new javax.swing.JLabel();
        txtTotalItem = new javax.swing.JTextField();
        lblValor10 = new javax.swing.JLabel();
        txtDescontoItem = new javax.swing.JTextField();
        lblValor11 = new javax.swing.JLabel();
        txtTotalNotaItem = new javax.swing.JTextField();
        btnAdicionar = new javax.swing.JButton();
        btnRemover = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblProduto = new javax.swing.JTable();
        btnExcluir = new javax.swing.JButton();
        btnSalvar = new javax.swing.JButton();
        btnFechar = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        setTitle("NOTA FISCAL DE ENTRADA");
        setPreferredSize(new java.awt.Dimension(680, 680));

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Nota Fiscal"));

        lbl_data3.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        lbl_data3.setText("Série:");

        txtNumNotaFiscal.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtNumNotaFiscalKeyTyped(evt);
            }
        });

        txtSerie.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtSerieActionPerformed(evt);
            }
        });
        txtSerie.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtSerieKeyTyped(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        jLabel1.setText("Número NF:");

        lbl_data2.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        lbl_data2.setText("Dt. Emissão:");

        txtDtEmissao.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtDtEmissaoKeyTyped(evt);
            }
        });

        txtDtReceb.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtDtRecebActionPerformed(evt);
            }
        });
        txtDtReceb.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtDtRecebFocusLost(evt);
            }
        });
        txtDtReceb.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtDtRecebKeyTyped(evt);
            }
        });

        lbl_data5.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        lbl_data5.setText("Dt. Receb.:");

        lbl_data6.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        lbl_data6.setText("CNPJ Fornec:");

        txtCNPJ.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCNPJActionPerformed(evt);
            }
        });
        txtCNPJ.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtCNPJFocusLost(evt);
            }
        });
        txtCNPJ.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtCNPJKeyTyped(evt);
            }
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtCNPJKeyPressed(evt);
            }
        });

        lbl_data7.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        lbl_data7.setText("Nome Fornecedor:");

        cbFornecedor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbFornecedorActionPerformed(evt);
            }
        });

        lblValor3.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        lblValor3.setText("Vlr. Total:");

        txtTotalProdutosNota.setEditable(false);
        txtTotalProdutosNota.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtTotalProdutosNotaFocusLost(evt);
            }
        });
        txtTotalProdutosNota.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtTotalProdutosNotaKeyTyped(evt);
            }
        });

        lblValor4.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        lblValor4.setText("Vlr. Desc:");

        txtDescontoNota.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtDescontoNotaFocusLost(evt);
            }
        });
        txtDescontoNota.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtDescontoNotaKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtDescontoNotaKeyTyped(evt);
            }
        });

        lblValor5.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        lblValor5.setText("Vlr. NF:");

        txtValorNota.setEditable(false);
        txtValorNota.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtValorNotaFocusLost(evt);
            }
        });
        txtValorNota.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtValorNotaKeyTyped(evt);
            }
        });

        lbl_data11.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        lbl_data11.setText("Num. Ped. Compra:");

        cbPedCompra.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbPedCompraActionPerformed(evt);
            }
        });

        dcRecebimento.setMaxSelectableDate(new java.util.Date(253370775711000L));
        dcRecebimento.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                dcRecebimentoKeyReleased(evt);
            }
            public void keyPressed(java.awt.event.KeyEvent evt) {
                dcRecebimentoKeyPressed(evt);
            }
        });

        lbl_data10.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        lbl_data10.setText("Dt. Receb.:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(265, 265, 265)
                                .addComponent(cbPedCompra, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(lbl_data7)
                                    .addComponent(cbFornecedor, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(lbl_data11)))
                        .addGap(13, 13, 13)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lbl_data6)
                            .addComponent(txtCNPJ, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lblValor3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtTotalProdutosNota, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(lblValor4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtDescontoNota, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(lblValor5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtValorNota, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtNumNotaFiscal, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(lbl_data3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(txtSerie, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtDtEmissao, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lbl_data2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtDtReceb, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lbl_data5))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lbl_data10)
                            .addComponent(dcRecebimento, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(60, Short.MAX_VALUE))
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {txtDtEmissao, txtDtReceb});

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lbl_data7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cbFornecedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lbl_data11)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cbPedCompra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lbl_data6)
                        .addGap(26, 26, 26))
                    .addComponent(txtCNPJ, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lbl_data2)
                            .addComponent(lbl_data5)
                            .addComponent(lbl_data10))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtDtEmissao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtDtReceb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtNumNotaFiscal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(lbl_data3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtSerie, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(dcRecebimento, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblValor3, javax.swing.GroupLayout.PREFERRED_SIZE, 13, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtTotalProdutosNota, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblValor4, javax.swing.GroupLayout.PREFERRED_SIZE, 13, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtDescontoNota, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblValor5, javax.swing.GroupLayout.PREFERRED_SIZE, 13, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtValorNota, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Itens Nota Fiscal"));

        lbl_data1.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        lbl_data1.setText("Tipo Produto:");

        cbTipo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Selecionar Tipo Produto" }));
        cbTipo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbTipoActionPerformed(evt);
            }
        });

        lbl_data8.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        lbl_data8.setText("Produto:");

        cbProduto.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Selecionar Produto" }));
        cbProduto.setEnabled(false);
        cbProduto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbProdutoActionPerformed(evt);
            }
        });

        lbl_data9.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        lbl_data9.setText("Unid. Med.");

        txtUnidadeItem.setEditable(false);
        txtUnidadeItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtUnidadeItemActionPerformed(evt);
            }
        });

        txtRefProdItem.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtRefProdItemFocusLost(evt);
            }
        });
        txtRefProdItem.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtRefProdItemKeyTyped(evt);
            }
        });

        lblValor6.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        lblValor6.setText("Ref. Produto");

        lblValor7.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        lblValor7.setText("Qtde:");

        txtQtdeItem.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtQtdeItemFocusLost(evt);
            }
        });
        txtQtdeItem.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtQtdeItemKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtQtdeItemKeyTyped(evt);
            }
        });

        lblValor8.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        lblValor8.setText("Vlr. Unit.:");

        txtValorUnitarioItem.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtValorUnitarioItemFocusLost(evt);
            }
        });
        txtValorUnitarioItem.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtValorUnitarioItemKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtValorUnitarioItemKeyTyped(evt);
            }
        });

        lblValor9.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        lblValor9.setText("Vlr. Total:");

        txtTotalItem.setEditable(false);
        txtTotalItem.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtTotalItemFocusLost(evt);
            }
        });
        txtTotalItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtTotalItemActionPerformed(evt);
            }
        });
        txtTotalItem.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtTotalItemKeyTyped(evt);
            }
        });

        lblValor10.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        lblValor10.setText("Vlr. Desc.:");

        txtDescontoItem.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtDescontoItemFocusLost(evt);
            }
        });
        txtDescontoItem.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtDescontoItemKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtDescontoItemKeyTyped(evt);
            }
        });

        lblValor11.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
        lblValor11.setText("Vlr. NF.:");

        txtTotalNotaItem.setEditable(false);
        txtTotalNotaItem.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtTotalNotaItemFocusLost(evt);
            }
        });
        txtTotalNotaItem.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtTotalNotaItemKeyTyped(evt);
            }
        });

        btnAdicionar.setText("Adicionar");
        btnAdicionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAdicionarActionPerformed(evt);
            }
        });

        btnRemover.setText("Remover");
        btnRemover.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoverActionPerformed(evt);
            }
        });

        tblProduto.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Item", "Produto", "U.Med.", "Qtde", "Vlr.Unit.", "Vlr.Total", "Vlr.Desc", "Vlr.NF."
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblProduto.getTableHeader().setReorderingAllowed(false);
        tblProduto.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                tblProdutoMousePressed(evt);
            }
        });
        jScrollPane1.setViewportView(tblProduto);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(lbl_data1)
                            .addComponent(cbTipo, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lbl_data8)
                            .addComponent(cbProduto, javax.swing.GroupLayout.PREFERRED_SIZE, 258, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(lbl_data9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(txtUnidadeItem, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblValor6)
                            .addComponent(txtRefProdItem, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblValor7)
                            .addComponent(txtQtdeItem, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblValor8)
                            .addComponent(txtValorUnitarioItem, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblValor9)
                            .addComponent(txtTotalItem, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel2Layout.createSequentialGroup()
                                        .addComponent(lblValor10)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 4, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(txtDescontoItem, javax.swing.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE))
                                .addGap(18, 18, 18)
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(lblValor11)
                                    .addComponent(txtTotalNotaItem, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(btnAdicionar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnRemover)))
                        .addGap(16, 16, 16))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addComponent(jScrollPane1)
                        .addContainerGap())))
        );

        jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {lblValor10, txtTotalItem, txtValorUnitarioItem});

        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(lbl_data9)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtUnidadeItem, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(lbl_data8)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cbProduto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(lbl_data1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cbTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(lblValor6, javax.swing.GroupLayout.PREFERRED_SIZE, 13, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtRefProdItem, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(lblValor7, javax.swing.GroupLayout.PREFERRED_SIZE, 13, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtQtdeItem, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(lblValor8, javax.swing.GroupLayout.PREFERRED_SIZE, 13, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtValorUnitarioItem, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(lblValor9, javax.swing.GroupLayout.PREFERRED_SIZE, 13, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtTotalItem, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(lblValor10, javax.swing.GroupLayout.PREFERRED_SIZE, 13, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtDescontoItem, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(lblValor11, javax.swing.GroupLayout.PREFERRED_SIZE, 13, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtTotalNotaItem, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAdicionar)
                    .addComponent(btnRemover))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        btnExcluir.setText("Excluir");

        btnSalvar.setText("Salvar");
        btnSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalvarActionPerformed(evt);
            }
        });

        btnFechar.setText("Fechar");
        btnFechar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFecharActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnExcluir)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnSalvar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnFechar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnExcluir)
                    .addComponent(btnSalvar)
                    .addComponent(btnFechar))
                .addContainerGap(83, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtSerieKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtSerieKeyTyped
        // TODO add your handling code here:
        String caracteres = "0987654321.,";

        if (!caracteres.contains(evt.getKeyChar() + "")) {
            evt.consume();
        }
    }//GEN-LAST:event_txtSerieKeyTyped

    private void txtSerieActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtSerieActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtSerieActionPerformed

    private void txtDtEmissaoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDtEmissaoKeyTyped
        String caracteres = "0987654321";

        if (!caracteres.contains(evt.getKeyChar() + "")) {
            evt.consume();
        }
    }//GEN-LAST:event_txtDtEmissaoKeyTyped

    private void txtDtRecebKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDtRecebKeyTyped
        // TODO add your handling code here:
        String caracteres = "0987654321";

        if (!caracteres.contains(evt.getKeyChar() + "")) {
            evt.consume();
        }
    }//GEN-LAST:event_txtDtRecebKeyTyped

    private void txtCNPJKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCNPJKeyTyped
        // TODO add your handling code here:
        String caracteres = "0987654321";

        if (!caracteres.contains(evt.getKeyChar() + "")) {
            evt.consume();
        }
    }//GEN-LAST:event_txtCNPJKeyTyped

    private void txtTotalProdutosNotaFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtTotalProdutosNotaFocusLost
        // TODO add your handling code here:
    }//GEN-LAST:event_txtTotalProdutosNotaFocusLost

    private void txtTotalProdutosNotaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTotalProdutosNotaKeyTyped
        String caracteres = "0987654321,.";

        if (!caracteres.contains(evt.getKeyChar() + "")) {

            evt.consume();

        }
    }//GEN-LAST:event_txtTotalProdutosNotaKeyTyped

    private void txtDescontoNotaFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtDescontoNotaFocusLost
        // TODO add your handling code here:
        calculaValorTotalNotaDesconto();
    }//GEN-LAST:event_txtDescontoNotaFocusLost

    private void txtDescontoNotaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDescontoNotaKeyTyped
        // TODO add your handling code here:
        String caracteres = "0987654321.,";

        if (!caracteres.contains(evt.getKeyChar() + "")) {
            evt.consume();
        }
    }//GEN-LAST:event_txtDescontoNotaKeyTyped

    private void txtValorNotaFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtValorNotaFocusLost
        // TODO add your handling code here:
    }//GEN-LAST:event_txtValorNotaFocusLost

    private void txtValorNotaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtValorNotaKeyTyped
        // TODO add your handling code here:
        String caracteres = "0987654321.,";

        if (!caracteres.contains(evt.getKeyChar() + "")) {
            evt.consume();
        }
    }//GEN-LAST:event_txtValorNotaKeyTyped

    private void cbTipoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbTipoActionPerformed
        if (cbTipo.getSelectedIndex() > 0) {
            limpaCamposItens();
            cbProduto.removeAllItems();
            populaListaProduto();
            cbProduto.setEnabled(true);
        } else {
            cbProduto.setEnabled(false);
            cbProduto.setSelectedIndex(0);
            limpaCamposItens();
        }
    }//GEN-LAST:event_cbTipoActionPerformed

    private void cbProdutoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbProdutoActionPerformed
        if (cbProduto.getSelectedIndex() > 0) {
            limpaCamposItens();

            txtUnidadeItem.setText(((ProdutoBean) modeloProduto.getSelectedItem()).getUnidadeMedida());

        } else {

            limpaCamposItens();
        }
    }//GEN-LAST:event_cbProdutoActionPerformed

    private void txtRefProdItemFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtRefProdItemFocusLost
        // TODO add your handling code here:
    }//GEN-LAST:event_txtRefProdItemFocusLost

    private void txtRefProdItemKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtRefProdItemKeyTyped
        // TODO add your handling code here:
    }//GEN-LAST:event_txtRefProdItemKeyTyped

    private void txtQtdeItemFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtQtdeItemFocusLost
        // TODO add your handling code here:        
        txtTotalItem.setText("");
        txtDescontoItem.setText("");
        txtTotalNotaItem.setText("");
        calculaTotalItem();
    }//GEN-LAST:event_txtQtdeItemFocusLost

    private void txtQtdeItemKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtQtdeItemKeyTyped
        // TODO add your handling code here:
        String caracteres = "0987654321.,";

        if (!caracteres.contains(evt.getKeyChar() + "")) {
            evt.consume();
        }
    }//GEN-LAST:event_txtQtdeItemKeyTyped

    private void txtValorUnitarioItemFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtValorUnitarioItemFocusLost
        // TODO add your handling code here:
        txtTotalItem.setText("");
        txtDescontoItem.setText("");
        txtTotalNotaItem.setText("");
        calculaTotalItem();
    }//GEN-LAST:event_txtValorUnitarioItemFocusLost

    private void txtValorUnitarioItemKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtValorUnitarioItemKeyTyped
        // TODO add your handling code here:
        String caracteres = "0987654321.,";

        if (!caracteres.contains(evt.getKeyChar() + "")) {
            evt.consume();
        }
    }//GEN-LAST:event_txtValorUnitarioItemKeyTyped

    private void txtTotalItemFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtTotalItemFocusLost
        // TODO add your handling code here:
    }//GEN-LAST:event_txtTotalItemFocusLost

    private void txtTotalItemKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTotalItemKeyTyped
        // TODO add your handling code here:
        String caracteres = "0987654321.,";

        if (!caracteres.contains(evt.getKeyChar() + "")) {
            evt.consume();
        }
    }//GEN-LAST:event_txtTotalItemKeyTyped

    private void txtDescontoItemFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtDescontoItemFocusLost
        // TODO add your handling code here:
        calculaTotalNotaItem();
    }//GEN-LAST:event_txtDescontoItemFocusLost

    private void txtDescontoItemKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDescontoItemKeyTyped
        // TODO add your handling code here:
        String caracteres = "0987654321.,";

        if (!caracteres.contains(evt.getKeyChar() + "")) {
            evt.consume();
        }
    }//GEN-LAST:event_txtDescontoItemKeyTyped

    private void txtTotalNotaItemFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtTotalNotaItemFocusLost
        // TODO add your handling code here:
    }//GEN-LAST:event_txtTotalNotaItemFocusLost

    private void txtTotalNotaItemKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTotalNotaItemKeyTyped
        // TODO add your handling code here:
        String caracteres = "0987654321.,";

        if (!caracteres.contains(evt.getKeyChar() + "")) {
            evt.consume();
        }
    }//GEN-LAST:event_txtTotalNotaItemKeyTyped

    private void tblProdutoMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblProdutoMousePressed

    }//GEN-LAST:event_tblProdutoMousePressed

    private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
        // TODO add your handling code here:
        if (validaCamposNotaFiscal()) {
            if (cadastraNotaFiscalEntrada()) {
                this.dispose();
                NotaFiscalEntradaView notaFiscalEntradaV = new NotaFiscalEntradaView();
                Global.principal.Desktop.add(notaFiscalEntradaV);
                CentralizarForm.centralizaForm(notaFiscalEntradaV);
                notaFiscalEntradaV.setVisible(true);
            }
        }
    }//GEN-LAST:event_btnSalvarActionPerformed

    private void txtDtRecebActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtDtRecebActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtDtRecebActionPerformed

    private void cbFornecedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbFornecedorActionPerformed
        // TODO add your handling code here:
        //System.out.println(comboNumPedido.getSize());
        listaDeItens = new ArrayList<>();
        modeloDeTabela.setNumRows(0);
        cbPedCompra.removeAllItems();
        cbPedCompra.addItem("");
        txtCNPJ.setText(((FornecedorBean) modeloForncedor.getSelectedItem()).getPfj());
        validaCNPJCPF();
        pesquisaPedidoFornecedor(((FornecedorBean) modeloForncedor.getSelectedItem()).getCodigo());

    }//GEN-LAST:event_cbFornecedorActionPerformed

    private void txtCNPJFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtCNPJFocusLost
        // TODO add your handling code here:

    }//GEN-LAST:event_txtCNPJFocusLost

    private void txtCNPJKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCNPJKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            pesquisaFornecedor(txtCNPJ.getText());
        }
    }//GEN-LAST:event_txtCNPJKeyPressed

    private void txtNumNotaFiscalKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNumNotaFiscalKeyTyped
        // TODO add your handling code here:
        
        String caracteres = "0987654321";

        if (!caracteres.contains(evt.getKeyChar() + "")) {
            evt.consume();
        }
    }//GEN-LAST:event_txtNumNotaFiscalKeyTyped

    private void txtQtdeItemKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtQtdeItemKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            txtTotalItem.setText("");
            txtDescontoItem.setText("");
            txtTotalNotaItem.setText("");
            calculaTotalItem();
        }
    }//GEN-LAST:event_txtQtdeItemKeyPressed

    private void txtValorUnitarioItemKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtValorUnitarioItemKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            txtTotalItem.setText("");
            txtDescontoItem.setText("");
            txtTotalNotaItem.setText("");
            calculaTotalItem();
        }
    }//GEN-LAST:event_txtValorUnitarioItemKeyPressed

    private void txtDescontoItemKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDescontoItemKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            calculaTotalNotaItem();
        }
    }//GEN-LAST:event_txtDescontoItemKeyPressed

    int item = 0;
    private void btnAdicionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAdicionarActionPerformed
        // TODO add your handling code here:
        if (validaCamposItem()) {
            adicionaItemPedido();
            modeloDeTabela.addRow(new Object[]{item, cbProduto.getSelectedItem(), txtUnidadeItem.getText(), txtQtdeItem.getText(), decimalFormato.format(Double.parseDouble(txtValorUnitarioItem.getText().replace(",", "."))), txtTotalItem.getText(), txtDescontoItem.getText().isEmpty() ? 0 : decimalFormato.format(Double.parseDouble(txtDescontoItem.getText().replace(",", "."))), txtTotalNotaItem.getText()});
            cbTipo.setSelectedIndex(0);
            calculaTotal();
        }
    }//GEN-LAST:event_btnAdicionarActionPerformed

    private void btnRemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoverActionPerformed
        // TODO add your handling code here:
        int linha = tblProduto.getSelectedRow();
        if (linha < 0) {
            JOptionPane.showMessageDialog(null, "Selecione um item na lista para remover", "ERRO", 0, new ImageIcon("imagens/cancelar.png"));
        } else {
            switch (JOptionPane.showConfirmDialog(null, "Remover Item " + listaDeItens.get(linha), "Remover item de pedido", JOptionPane.YES_NO_OPTION)) {
                case 0:
                    modeloDeTabela.removeRow(linha);
                    listaDeItens.remove(linha);
                    calculaTotal();
                    break;
            }
        }
    }//GEN-LAST:event_btnRemoverActionPerformed

    private void txtDescontoNotaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDescontoNotaKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            calculaValorTotalNotaDesconto();
        }
    }//GEN-LAST:event_txtDescontoNotaKeyPressed

    private void btnFecharActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFecharActionPerformed
        // TODO add your handling code here:
        switch (JOptionPane.showConfirmDialog(null, "Deseja sair", "Sair", JOptionPane.YES_NO_OPTION)) {
            case 0:
                this.dispose();
                break;
        }
    }//GEN-LAST:event_btnFecharActionPerformed

    private void txtUnidadeItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtUnidadeItemActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtUnidadeItemActionPerformed

    private void txtTotalItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtTotalItemActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtTotalItemActionPerformed

    private void txtCNPJActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCNPJActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCNPJActionPerformed

    private void cbPedCompraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbPedCompraActionPerformed
        // TODO add your handling code here:
        modeloDeTabela.setNumRows(0);
        if (cbPedCompra.getSelectedIndex() > 0) {
            pesquisaPedido(((FornecedorBean) modeloForncedor.getSelectedItem()).getCodigo(), Integer.parseInt(comboNumPedido.getSelectedItem().toString()));
        }
        
    }//GEN-LAST:event_cbPedCompraActionPerformed

    private void dcRecebimentoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_dcRecebimentoKeyPressed
        // TODO add your handling code here:
        
    }//GEN-LAST:event_dcRecebimentoKeyPressed

    private void txtDtRecebFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtDtRecebFocusLost
        // TODO add your handling code here:
       
        
    }//GEN-LAST:event_txtDtRecebFocusLost

    private void dcRecebimentoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_dcRecebimentoKeyReleased
        // TODO add your handling code here:
       
              
    }//GEN-LAST:event_dcRecebimentoKeyReleased


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdicionar;
    private javax.swing.JButton btnExcluir;
    private javax.swing.JButton btnFechar;
    private javax.swing.JButton btnRemover;
    private javax.swing.JButton btnSalvar;
    private javax.swing.JComboBox cbFornecedor;
    private javax.swing.JComboBox cbPedCompra;
    private javax.swing.JComboBox cbProduto;
    private javax.swing.JComboBox cbTipo;
    private com.toedter.calendar.JDateChooser dcRecebimento;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblValor10;
    private javax.swing.JLabel lblValor11;
    private javax.swing.JLabel lblValor3;
    private javax.swing.JLabel lblValor4;
    private javax.swing.JLabel lblValor5;
    private javax.swing.JLabel lblValor6;
    private javax.swing.JLabel lblValor7;
    private javax.swing.JLabel lblValor8;
    private javax.swing.JLabel lblValor9;
    private javax.swing.JLabel lbl_data1;
    private javax.swing.JLabel lbl_data10;
    private javax.swing.JLabel lbl_data11;
    private javax.swing.JLabel lbl_data2;
    private javax.swing.JLabel lbl_data3;
    private javax.swing.JLabel lbl_data5;
    private javax.swing.JLabel lbl_data6;
    private javax.swing.JLabel lbl_data7;
    private javax.swing.JLabel lbl_data8;
    private javax.swing.JLabel lbl_data9;
    private javax.swing.JTable tblProduto;
    private javax.swing.JTextField txtCNPJ;
    private javax.swing.JTextField txtDescontoItem;
    private javax.swing.JTextField txtDescontoNota;
    private javax.swing.JTextField txtDtEmissao;
    private javax.swing.JTextField txtDtReceb;
    private javax.swing.JTextField txtNumNotaFiscal;
    private javax.swing.JTextField txtQtdeItem;
    private javax.swing.JTextField txtRefProdItem;
    private javax.swing.JTextField txtSerie;
    private javax.swing.JTextField txtTotalItem;
    private javax.swing.JTextField txtTotalNotaItem;
    private javax.swing.JTextField txtTotalProdutosNota;
    private javax.swing.JTextField txtUnidadeItem;
    private javax.swing.JTextField txtValorNota;
    private javax.swing.JTextField txtValorUnitarioItem;
    // End of variables declaration//GEN-END:variables

    public void populaTipoProduto() {
        listaTipoProd = new ArrayList<>();
        populaListaTipoProduto(listaTipoProd);
        for (TipoProdutoBean tipoProdutoBeans : listaTipoProd) {
            cbTipo.addItem(tipoProdutoBeans);
        }
    }

    public void limpaCamposItens() {
        txtDescontoItem.setText("");
        txtQtdeItem.setText("");
        txtRefProdItem.setText("");
        txtTotalItem.setText("");
        txtUnidadeItem.setText("");
        txtValorUnitarioItem.setText("");
        txtTotalNotaItem.setText("");
    }

    public void populaListaProduto() {
        if (cbTipo.getSelectedIndex() > 0) {
            listaProduto = new ArrayList<>();
            pesquisaProdutos(((TipoProdutoBean) modeloTipoProd.getSelectedItem()).getCodigo(), listaProduto);
            cbProduto.addItem("Selecionar Produto");

            for (ProdutoBean prdutoBeans : listaProduto) {
                cbProduto.addItem(prdutoBeans);
            }

        } else {

            cbProduto.setSelectedIndex(0);
        }
    }

    public void populaListaTipoProduto(List<TipoProdutoBean> lista) {
        String SQLSelection = "select \n"
                + "  `tprd_id`,\n"
                + "  `tprd_descr`,\n"
                + "  `tprd_stt_pizza` \n"
                + "from\n"
                + "  `pizzaria`.`tipo_prod` \n"
                + "where tprd_stt_pizza='N';";

        try (PreparedStatement pstm = ConectaBanco.getConnection().prepareStatement(SQLSelection)) {

            ResultSet rs = pstm.executeQuery();

            while (rs.next()) {
                TipoProdutoBean novo = new TipoProdutoBean();
                novo.setCodigo(rs.getInt("tprd_id"));
                novo.setDescricao(rs.getString("tprd_descr"));
                lista.add(novo);
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Impossível Carregar Lista " + ex, "Erro de SQL ", 0, new ImageIcon("imagens/cancelar.png"));
        }
    }

    public void pesquisaProdutos(int codigo, List<ProdutoBean> listaDeItens) {
        try {
            String SQLPesquisa = "SELECT \n"
                    + "  t.`tprd_id`,\n"
                    + "  t.`tprd_descr`,\n"
                    + "  p.`prd_prod`,\n"
                    + "  p.`prd_prod_venda`,\n"
                    + "  p.`prd_descr`,\n"
                    + "  p.`prd_unid_med`,\n"
                    + "  p.`prod_estocavel`\n "
                    //                    + "  c.`sdoe_qtd_sdo_atu` \n"
                    + "FROM\n"
                    + "  `pizzaria`.`tipo_prod` t \n"
                    + "  JOIN `pizzaria`.`produtos` p \n"
                    + "    ON p.`prd_tipo_prod`=t.tprd_id \n"
                    //                     + "  JOIN `pizzaria`.`saldo_estoque` c \n"
                    //                    + "    ON c.sdoe_cod_prod = p.prd_prod \n"
                    + "WHERE t.`tprd_id` = '" + codigo + "' and p.`prod_estocavel` ='S';";

            PreparedStatement pstmt = ConectaBanco.getConnection().prepareStatement(SQLPesquisa);
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                ProdutoBean novo = new ProdutoBean();
                novo.setCodigo(rs.getInt("prd_prod"));
                novo.setDescricao(rs.getString("prd_descr"));
                novo.getTipoProduto().setCodigo(rs.getInt("tprd_id"));
                novo.getTipoProduto().setDescricao(rs.getString("tprd_descr"));
                novo.setEstocavel(rs.getString("prod_estocavel").charAt(0));
                novo.setUnidadeMedida(rs.getString("prd_unid_med"));

                listaDeItens.add(novo);
            }
        } catch (SQLException ex) {
            Logger.getLogger(PedidoModel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void populaListaFornecedor() {
        listaFornec = new ArrayList<>();
        populaFornecedor(listaFornec);
        for (FornecedorBean fornecedor : listaFornec) {
            cbFornecedor.addItem(fornecedor);
        }
    }

    public void populaFornecedor(List<FornecedorBean> listaFornec) {

        try {

            String SQLSelection = "select * from fornecedor ;";
            PreparedStatement pstm = ConectaBanco.getConnection().prepareStatement(SQLSelection);

            ResultSet rs = pstm.executeQuery();
            while (rs.next()) {
                FornecedorBean novo = new FornecedorBean();
                novo.setNome(rs.getString("for_nome"));
                novo.setCodigo(rs.getInt("for_id_fornec"));
                novo.setPfj(rs.getString("for_cod_pfj"));

                listaFornec.add(novo);
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Erro no banco de dados! " + ex, "Erro de SQL", 0, new ImageIcon("imagens/cancelar.png"));
        }

    }

    public void validaCNPJCPF() {
        if (ValidaCNPJ.isCNPJ(txtCNPJ.getText())) {
            txtCNPJ.setText(ValidaCNPJ.imprimeCNPJ(txtCNPJ.getText()));
        } else if (ValidaCPF.isCPF(txtCNPJ.getText())) {
            txtCNPJ.setText(ValidaCPF.imprimeCPF(txtCNPJ.getText()));
        }

    }

    public void pesquisaFornecedor(String cnpjcpf) {

        try {

            String SQLSelection = "select * from fornecedor where for_cod_pfj = ?;";
            PreparedStatement pstm = ConectaBanco.getConnection().prepareStatement(SQLSelection);
            pstm.setString(1, cnpjcpf);
            ResultSet rs = pstm.executeQuery();
            if (rs.next()) {
                FornecedorBean novo = new FornecedorBean();
                novo.setNome(rs.getString("for_nome"));;
                novo.setCodigo(rs.getInt("for_id_fornec"));
                novo.setPfj(rs.getString("for_cod_pfj"));
                modeloForncedor.setSelectedItem(novo);

            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Impossível preencher os campos " + ex, "Erro de SQL", 0, new ImageIcon("imagens/cancelar.png"));
        }

    }

    public void calculaTotalItem() {
        if (!txtQtdeItem.getText().isEmpty() && !txtValorUnitarioItem.getText().isEmpty()) {
            txtTotalItem.setText(decimalFormato.format(Double.parseDouble(txtValorUnitarioItem.getText().replace(",", ".")) * Double.parseDouble(txtQtdeItem.getText().replace(",", "."))));
            txtTotalNotaItem.setText(decimalFormato.format(Double.parseDouble(txtValorUnitarioItem.getText().replace(",", ".")) * Double.parseDouble(txtQtdeItem.getText().replace(",", "."))));
        }
    }

    public void calculaTotalNotaItem() {
        if (!txtQtdeItem.getText().isEmpty() && !txtValorUnitarioItem.getText().isEmpty()) {
            txtTotalItem.setText(decimalFormato.format(Double.parseDouble(txtValorUnitarioItem.getText().replace(",", ".")) * Double.parseDouble(txtQtdeItem.getText().replace(",", "."))));
        }
        if (!txtTotalItem.getText().isEmpty() && !txtDescontoItem.getText().isEmpty()) {
            txtTotalNotaItem.setText(decimalFormato.format(Double.parseDouble(txtTotalItem.getText().replace(",", ".")) - Double.parseDouble(txtDescontoItem.getText().replace(",", "."))));
        }
    }

    public boolean validaCamposItem() {
        if (cbProduto.getSelectedIndex() <= 0) {
            JOptionPane.showMessageDialog(null, "Selecione um produto!");
            cbProduto.requestFocus();
            return false;
        }
        if (txtQtdeItem.getText().isEmpty()) {
            JOptionPane.showMessageDialog(null, "Campo Quantidade não pode ser vazio!");
            txtQtdeItem.requestFocus();
            return false;
        }
        if (txtValorUnitarioItem.getText().isEmpty()) {
            JOptionPane.showMessageDialog(null, "Campo Valor Unitário não pode ser vazio!");
            txtValorUnitarioItem.requestFocus();
            return false;
        }
        if (txtTotalItem.getText().isEmpty()) {
            return false;

        }
        if (txtTotalNotaItem.getText().isEmpty()) {
            return false;
        }
        return true;
    }

    public void adicionaItemPedido() {
        ItemNotaFiscalEntradaBean itemPedido = new ItemNotaFiscalEntradaBean();
        itemPedido.setCodigoProduto(((ProdutoBean) cbProduto.getSelectedItem()).getCodigo());
        itemPedido.setPrecoUnitario(Double.parseDouble(txtValorUnitarioItem.getText().replace(",", ".")));
        itemPedido.setQuantidade(Double.parseDouble(txtQtdeItem.getText().replace(",", ".")));
        itemPedido.setPrecoTotalItem(Double.parseDouble(txtTotalItem.getText().replace(",", ".")));
        itemPedido.setCodigoItem(++item);
        itemPedido.setPrecoTotalNotaFiscalItem(Double.parseDouble(txtTotalNotaItem.getText().replace(",", ".")));
        itemPedido.setItemProdutoBean((ProdutoBean) cbProduto.getSelectedItem());
        itemPedido.setValotDesconto((txtDescontoItem.getText().isEmpty() ? 0 : Double.parseDouble(txtDescontoItem.getText().replace(",", "."))));
        itemPedido.setRefItemProduto(txtRefProdItem.getText());

        listaDeItens.add(itemPedido);
    }

    public void calculaTotal() {
        double totalNotaFiscal = 0;
        for (ItemNotaFiscalEntradaBean listaDeIten : listaDeItens) {
            totalNotaFiscal += listaDeIten.getPrecoTotalNotaFiscalItem();
        }

        txtTotalProdutosNota.setText(decimalFormato.format(totalNotaFiscal).replace(",", "."));
        txtValorNota.setText(decimalFormato.format(totalNotaFiscal).replace(",", "."));
        txtDescontoNota.setText("");
    }

    public void calculaValorTotalNotaDesconto() {
        if (!txtTotalProdutosNota.getText().isEmpty() && !txtDescontoNota.getText().isEmpty()) {
            txtValorNota.setText(decimalFormato.format(Double.parseDouble(txtTotalProdutosNota.getText().replace(",", ".")) - Double.parseDouble(txtDescontoNota.getText().replace(",", "."))));
        }
    }

    public boolean validaCamposNotaFiscal() {
        if (txtNumNotaFiscal.getText().isEmpty()) {
            JOptionPane.showMessageDialog(null, "Campo Num. Nota Fiscal não pode ser vazio!");
            txtNumNotaFiscal.requestFocus();
            return false;
        }
        if (txtSerie.getText().isEmpty()) {
            JOptionPane.showMessageDialog(null, "Campo Série não pode ser vazio!");
            txtSerie.requestFocus();
            return false;
        }

        if (txtDtReceb.getText().equals("  /  /    ")) {
            JOptionPane.showMessageDialog(null, "Campo Data Recebimento não pode ser vazio!");
            txtDtReceb.requestFocus();
            return false;
        }
        if (txtCNPJ.getText().isEmpty()) {
            JOptionPane.showMessageDialog(null, "Campo CNPJ não pode ser vazio!");
            txtCNPJ.requestFocus();
            return false;
        }

        if (txtTotalProdutosNota.getText().isEmpty()) {
            JOptionPane.showMessageDialog(null, "Adicione pelo menos um Item na Compra");
            return false;
        }
        if (txtValorNota.getText().isEmpty()) {
            JOptionPane.showMessageDialog(null, "Erro de Preenchimento!");
            return false;
        }

        return true;
    }

    public boolean cadastraNotaFiscalEntrada() {
        Date data = new Date();
        SimpleDateFormat formatoData = new SimpleDateFormat("yyyy-MM-dd");
        try {
            String SQLInserePedido = "insert into `pizzaria`.`nf_entrada`\n"
                    + "            (`nfe_nro_nf`,\n"
                    + "             `nfe_ser`,\n"
                    + "             `nfe_cod_forn`,\n"
                    + "             `nfe_dt_movto`,\n"
                    + "             `nfe_vlr_tot_prod`,\n"
                    + "             `nfe_vlr_nf`,\n"
                    + "             `nfe_vlr_desc`,\n"
                    + "             `nfe_dt_emis`,\n"
                    + "             `nfe_dt_receb`,\n"
                    + "             `nfe_ped_compra`,\n"
                    + "             `nfe_vlr_imposto`,\n"
                    + "             `nfe_id_usuario`)\n"
                    + "values (?,\n"
                    + "        ?,\n"
                    + "        ?,\n"
                    + "        ?,\n"
                    + "        ?,\n"
                    + "        ?,\n"
                    + "        ?,\n"
                    + "        ?,\n"
                    + "        ?,\n"
                    + "        ?,\n"
                    + "        ?,\n"
                    + "        ?);";
            PreparedStatement pstmt = ConectaBanco.getConnection().prepareStatement(SQLInserePedido);

            pstmt.setString(1, txtNumNotaFiscal.getText());
            pstmt.setInt(2, Integer.parseInt(txtSerie.getText()));
            pstmt.setInt(3, ((FornecedorBean) cbFornecedor.getSelectedItem()).getCodigo());
            pstmt.setString(4, formatoData.format(data));
            pstmt.setDouble(5, Double.parseDouble(txtTotalProdutosNota.getText()));
            pstmt.setDouble(6, Double.parseDouble(txtValorNota.getText()));
            pstmt.setDouble(7, txtDescontoNota.getText().isEmpty() ? 0 : Double.parseDouble(txtDescontoNota.getText()));
            pstmt.setString(8, VerificarData.converteParaSql(txtDtEmissao.getText()));
            pstmt.setString(9, VerificarData.converteParaSql(txtDtReceb.getText()));
            pstmt.setInt(10, cbPedCompra.getSelectedIndex()==0 ? 0 : Integer.parseInt(comboNumPedido.getSelectedItem().toString()));

            pstmt.setDouble(11, 0);
            pstmt.setString(12, Global.usuario.getLogin());
            pstmt.execute();

            if (cadastrarItens() && atualizaEstoque()) {
                ConectaBanco.getConnection().commit();
                JOptionPane.showMessageDialog(null, "Nota Fiscal Entrada realizado com sucesso", "Cadastro efetivado", 1, new ImageIcon("imagens/ticado.png"));
                return true;
            } else {
                ConectaBanco.closeConnection();
                return false;
            }

        } catch (SQLException ex) {
            try {
                ConectaBanco.getConnection().rollback();
                JOptionPane.showMessageDialog(null, "Impossível Cadastrar Pedido" + ex, "Erro de SQL", 0, new ImageIcon("imagens/cancelar.png"));
            } catch (SQLException ex1) {
                Logger.getLogger(PedidoModel.class.getName()).log(Level.SEVERE, null, ex1);
            }
            return false;
        }
    }

    public boolean cadastrarItens() {

        for (int i = 0; i < listaDeItens.size(); i++) {
            try {

                String SQLInsertItens = "insert into `pizzaria`.`item_nf_entrada`\n"
                        + "            (`nfei_nro_nf`,\n"
                        + "             `nfei_ser`,\n"
                        + "             `nfei_cod_forn`,\n"
                        + "             `nfei_cod_item`,\n"
                        + "             `nfei_cod_prod`,\n"
                        + "             `nfei_qtde`,\n"
                        + "             `nfei_vlr_unit`,\n"
                        + "             `nfei_vlr_desc`,\n"
                        + "             `nfei_ref_prod`,\n"
                        + "             `nfei_vlr_nf`,\n"
                        + "             `nfei_vlr_tot_prod`)\n"
                        + "values (?,\n"
                        + "        ?,\n"
                        + "        ?,\n"
                        + "        ?,\n"
                        + "        ?,\n"
                        + "        ?,\n"
                        + "        ?,\n"
                        + "        ?,\n"
                        + "        ?,\n"
                        + "        ?,\n"
                        + "       ?);";

                PreparedStatement pstmt = ConectaBanco.getConnection().prepareStatement(SQLInsertItens);
                pstmt.setString(1, txtNumNotaFiscal.getText());
                pstmt.setInt(2, Integer.parseInt(txtSerie.getText()));
                pstmt.setInt(3, ((FornecedorBean) cbFornecedor.getSelectedItem()).getCodigo());
                pstmt.setInt(4, listaDeItens.get(i).getCodigoItem());
                pstmt.setInt(5, listaDeItens.get(i).getCodigoProduto());
                pstmt.setDouble(6, listaDeItens.get(i).getQuantidade());
                pstmt.setDouble(7, listaDeItens.get(i).getPrecoUnitario());
                pstmt.setDouble(8, listaDeItens.get(i).getValotDesconto());
                pstmt.setString(9, listaDeItens.get(i).getRefItemProduto());
                pstmt.setDouble(10, listaDeItens.get(i).getPrecoTotalItem());
                pstmt.setDouble(11, listaDeItens.get(i).getPrecoTotalNotaFiscalItem());
                pstmt.execute();

            } catch (SQLException ex) {
                Logger.getLogger(PedidoModel.class.getName()).log(Level.SEVERE, null, ex);
                try {
                    ConectaBanco.getConnection().rollback();
                    JOptionPane.showMessageDialog(null, "Impossível Cadastrar Item" + ex, "Erro de SQL", 0, new ImageIcon("imagens/cancelar.png"));

                } catch (SQLException ex1) {
                    Logger.getLogger(PedidoModel.class.getName()).log(Level.SEVERE, null, ex1);
                }
                return false;
            }
        }

        return true;
    }

    public boolean atualizaEstoque() {
        Date data = new Date();
        SimpleDateFormat formatoData = new SimpleDateFormat("yyyy-MM-dd");

        for (int i = 0; i < listaDeItens.size(); i++) {
            AtualizaMovimentoEstoqueBean novo = new AtualizaMovimentoEstoqueBean();

            novo.setDataMovimento(formatoData.format(data));
            novo.setNumeroDocumento(txtNumNotaFiscal.getText());
            novo.setProdutoBean(listaDeItens.get(i).getItemProdutoBean());
            novo.setQuantidadeProduto(listaDeItens.get(i).getQuantidade());
            novo.setTipoMovimento(3);

            if (!Estoque.atualizaMovimentoEstoque(novo)) {
                try {
                    ConectaBanco.getConnection().rollback();
                } catch (SQLException ex1) {
                    Logger.getLogger(PedidoModel.class.getName()).log(Level.SEVERE, null, ex1);
                }
                return false;
            }

        }
        return true;
    }

    public void pesquisaPedido(int codigoFornec, int codigoPedido) {

        String SQLSelection = "SELECT\n"
                + "  `pedc_cod`,\n"
                + "  `pedc_data`,\n"
                + "  `pedc_vlr_tot`,\n"
                + "  `pedc_vlr_desc`,\n"
                + "  `pedc_cod_fornec`,\n"
                + "  `pedc_id_usuario`,\n"
                + "  `pedc_tp_ped_cotacao`,\n"
                + "  `pedc_situacao`,\n"
                + "  `pedc_dt_entrega`,\n"
                + "  `pedc_forma_pagto`,\n"
                + "  `pedc_cond_pagto`,\n"
                + "  `pedc_obs`,\n"
                + "  `pedc_vlr_liq`\n"
                + "FROM `pizzaria`.`ped_compra`\n"
                + "WHERE pedc_cod_fornec = ? and pedc_cod = ? "
                + "LIMIT 0, 1000;";

        try (PreparedStatement pstm = ConectaBanco.getConnection().prepareStatement(SQLSelection)) {

            pstm.setInt(1, codigoFornec);
            pstm.setInt(2, codigoPedido);
            ResultSet rs = pstm.executeQuery();
            if (rs.next()) {

                txtDtEmissao.setText(VerificarData.converteParaJAVA(rs.getString("pedc_data")));
                txtTotalProdutosNota.setText(rs.getString("pedc_vlr_tot"));
                txtDescontoNota.setText(rs.getString("pedc_vlr_desc"));
                txtValorNota.setText(rs.getString("pedc_vlr_liq"));
                

                pesquisaItensPedido(codigoPedido);
            }

        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Impossível preencher os campos " + ex, "Erro de SQL", 0, new ImageIcon("imagens/cancelar.png"));
        }

    }

    public void pesquisaItensPedido(int codigoPedido) {

        String SQLSelection = "SELECT\n"
                + "  `pedci_cod_ped`,\n"
                + "  `pedci_item`,\n"
                + "  `pedci_cod_prod`,\n"
                + "  `pedci_qtde`,\n"
                + "  `pedci_vlr_unit`,\n"
                + "  `pedci_vlr_desc`,\n"
                + "  `pedci_vlr_tot`,\n"
                + "  `pedci_cod_ref_prod`,\n"
                +" pedci_vlr_liq, "
                + "  `pedci_situacao`\n"
                + "FROM `pizzaria`.`item_ped_compra`\n"
                + "WHERE pedci_cod_ped = ?\n"
                + "LIMIT 0, 1000;";

        

        try (PreparedStatement pstm = ConectaBanco.getConnection().prepareStatement(SQLSelection)) {

            pstm.setInt(1, codigoPedido);
            ResultSet rs = pstm.executeQuery();
            while (rs.next()) {

//                //JOptionPane.showMessageDialog(null, rs.getString("pedci_cod_ped"));    //estou pegando da tabela Nf_entrada  acho que voce não entendeu direito  o campo ped compra vai buscar o pedido feito na tela de pedido de compra que voce fez hummm.       
//                txtRefProdItem.setText(rs.getString("pedci_cod_ref_prod"));
//                txtQtdeItem.setText(rs.getString("pedci_qtde"));
//                txtUnidadeItem.setText(rs.getString("pedci_vlr_unit"));
//                txtTotalItem.setText(rs.getString("pedci_vlr_tot"));//a data não vem!essa data de recebimento quem coloca é o usuario qunado cadastrar a nota fiscal.
//                //    JOptionPane.showMessageDialog(null, rs.getString("nfe_dt_receb"));
//               txtDescontoItem.setText(rs.getString("pedci_vlr_desc"));
//                txtDescontoNota.setText(rs.getString("nfe_vlr_desc"));
//                txtTotalNotaItem.setText(rs.getString("pedci_vlr_tot"));
                
                ItemNotaFiscalEntradaBean itemPedido = new ItemNotaFiscalEntradaBean();
                itemPedido.setCodigoProduto(rs.getInt("pedci_cod_prod"));//ok
                itemPedido.setPrecoUnitario(rs.getDouble("pedci_vlr_unit"));
                itemPedido.setQuantidade(Double.parseDouble(rs.getString("pedci_qtde")));
                itemPedido.setPrecoTotalItem(rs.getDouble("pedci_vlr_tot"));
                itemPedido.setCodigoItem(rs.getInt("pedci_item"));
                itemPedido.setPrecoTotalNotaFiscalItem(rs.getDouble("pedci_vlr_liq"));
                itemPedido.setItemProdutoBean(pesquisaProdutos(rs.getInt("pedci_cod_prod")));
                itemPedido.setValotDesconto(rs.getDouble("pedci_vlr_desc"));
                itemPedido.setRefItemProduto(rs.getString("pedci_cod_ref_prod"));
                 
                
                listaDeItens.add(itemPedido);
                

                modeloDeTabela.addRow(new Object[]{itemPedido.getCodigoItem(), itemPedido.getItemProdutoBean(), itemPedido.getItemProdutoBean().getUnidadeMedida(), itemPedido.getQuantidade(), itemPedido.getPrecoUnitario(), itemPedido.getPrecoTotalItem(), itemPedido.getValotDesconto(), itemPedido.getPrecoTotalNotaFiscalItem()});
            }

        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Impossível preencher os campos aqui " + ex, "Erro de SQL", 0, new ImageIcon("imagens/cancelar.png"));
        }

    }
    
    public ProdutoBean pesquisaProdutos(int codigo) {
        ProdutoBean novoProd = new ProdutoBean();
        try {
            String SQLPesquisa = "SELECT \n"
                    + "  t.`tprd_id`,\n"
                    + "  t.`tprd_descr`,\n"
                    + "  p.`prd_prod`,\n"
                    + "  p.`prd_prod_venda`,\n"
                    + "  p.`prd_descr`,\n"
                    + "  p.`prd_unid_med`,\n"
                    + "  p.`prod_estocavel`\n "
                    //                    + "  c.`sdoe_qtd_sdo_atu` \n"
                    + "FROM\n"
                    + "  `pizzaria`.`tipo_prod` t \n"
                    + "  JOIN `pizzaria`.`produtos` p \n"
                    + "    ON p.`prd_tipo_prod`=t.tprd_id \n"
                    //                     + "  JOIN `pizzaria`.`saldo_estoque` c \n"
                    //                    + "    ON c.sdoe_cod_prod = p.prd_prod \n"
                    + "WHERE p.`prd_prod` = '" + codigo + "' ;";

            PreparedStatement pstmt = ConectaBanco.getConnection().prepareStatement(SQLPesquisa);
            ResultSet rs = pstmt.executeQuery();
            
            if (rs.next()) {
                
                novoProd.setCodigo(rs.getInt("prd_prod"));
                novoProd.setDescricao(rs.getString("prd_descr"));
                novoProd.getTipoProduto().setCodigo(rs.getInt("tprd_id"));
                novoProd.getTipoProduto().setDescricao(rs.getString("tprd_descr"));
                novoProd.setEstocavel(rs.getString("prod_estocavel").charAt(0));
                novoProd.setUnidadeMedida(rs.getString("prd_unid_med"));

                
            }
        } catch (SQLException ex) {
            Logger.getLogger(PedidoModel.class.getName()).log(Level.SEVERE, null, ex);
        }
        return novoProd;
    }
    

    public void pesquisaPedidoFornecedor(int codigo) {
        String SQLSelection = "SELECT\n"
                + "  `pedc_cod`,\n"
                + "  `pedc_data`,\n"
                + "  `pedc_vlr_tot`,\n"
                + "  `pedc_vlr_desc`,\n"
                + "  `pedc_cod_fornec`,\n"
                + "  `pedc_id_usuario`,\n"
                + "  `pedc_tp_ped_cotacao`,\n"
                + "  `pedc_situacao`,\n"
                + "  `pedc_dt_entrega`,\n"
                + "  `pedc_forma_pagto`,\n"
                + "  `pedc_cond_pagto`,\n"
                + "  `pedc_obs`,\n"
                + "  `pedc_vlr_liq`\n"
                + "FROM `pizzaria`.`ped_compra`\n"
                + "WHERE pedc_cod_fornec =?\n"
                + "LIMIT 0, 1000;";

        try (PreparedStatement pstm = ConectaBanco.getConnection().prepareStatement(SQLSelection)) {

            pstm.setInt(1, codigo);
            ResultSet rs = pstm.executeQuery();
            while (rs.next()) {

                cbPedCompra.addItem(rs.getInt("pedc_cod"));

            }

        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Impossível preencher os campos aqui " + ex, "Erro de SQL", 0, new ImageIcon("imagens/cancelar.png"));
        }
    }

}
